package socks;

import java.io.BufferedOutputStream;


import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import android.util.Log;


public class OutputStreamWrapper extends FilterOutputStream {
	private int count = 0;//写了多少个字节

	public OutputStreamWrapper(OutputStream out) {
		super(out);
	}
	
	/**
	 * 第一位是要写的随机字节个数+6
	 * @throws IOException
	 */
	private void writeHead() throws IOException {
		int randomCount = new Random().nextInt( 20 );
		super.write( randomCount + 6 );
		count ++;
		for( int i=0; i< randomCount; i++) {
			super.write( new Random().nextInt( 127 ) );
			count ++;
		}
		Log.d(InputStreamWrapper.class.getName(),"OutputStreamWrapper write head:" + randomCount);
	}

	public void write(int oneByte) throws IOException {
		if( count == 0 ) {
			writeHead();
		}
		
		super.write( EncodeUtil.encode( oneByte, count) );
		Log.i(OutputStreamWrapper.class.getName(),"OutputStreamWrapper:" + oneByte + "=>" + (EncodeUtil.encode( oneByte, count))  + ";count=" + count);
		if(  oneByte >= 0 && oneByte <= 255 ) {
			count ++;
		}
		return;
	}
	
	
    public void write(byte[] buffer, int offset, int length) throws IOException {
    	if( count == 0 ) {
			writeHead();
		}
    	
    	EncodeUtil.encode( buffer , offset, length, this.count);
        super.out.write( buffer,  offset,  length);
        String debugString = "";
        for( int i=0; i < length; i++ ) {
        	debugString = debugString + "|" + buffer[offset + i];
        }
        Log.d(OutputStreamWrapper.class.getName(),"OutputStreamWrapper3:length=" + length + ";count=" + count + ";debugString=" + debugString + ";String" + new String(buffer,  offset,  length)  );
        count = count + length;
    }
    
    public void write(byte[] buffer) throws IOException {
        // BEGIN android-note
        // changed array notation to be consistent with the rest of harmony
        // END android-note
        write(buffer, 0, buffer.length);
    }
    
    public static byte norByte(byte b ) {

    	return (byte)(~ b);
	}
}
